package com.sbpm.crmbpm.client.forms.controls;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.BeforeSelectionEvent;
import com.google.gwt.event.logical.shared.BeforeSelectionHandler;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.sbpm.crmbpm.client.grid.CompanyColumnModelFactory;
import com.sbpm.crmbpm.client.handlers.LoadCompanyCallback;
import com.sbpm.crmbpm.client.services.CompanyManagement;
import com.sbpm.crmbpm.client.services.CompanyManagementAsync;
import com.sbpm.crmbpm.shared.data.client.Company;
import com.sencha.gxt.cell.core.client.form.ComboBoxCell;
import com.sencha.gxt.core.client.IdentityValueProvider;
import com.sencha.gxt.core.client.XTemplates;
import com.sencha.gxt.data.client.loader.RpcProxy;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.data.shared.loader.*;
import com.sencha.gxt.widget.core.client.ListView;
import com.sencha.gxt.widget.core.client.form.ComboBox;

public class CompanyComboBox extends ComboBox<Company>
{

    private static final CompanyManagementAsync companyManagement = GWT.create( CompanyManagement.class );

    interface CompanyTemplate extends XTemplates
    {
        @XTemplates.XTemplate("<div class=''><h3><span>{companyName}<br />ИНН {companyInn}</span></h3></div>")
        SafeHtml render(String companyName, String companyInn);
    }

    private static final CompanyTemplate template = GWT.create(CompanyTemplate.class);

    private static final ListStore<Company> listStore = new ListStore<Company>( CompanyColumnModelFactory.PROPS.key() );

    private static final ListView<Company, Company> listView = new ListView<Company, Company>(listStore, new IdentityValueProvider<Company>());

    private static final ComboBoxCell<Company> comboCell = new ComboBoxCell<Company>(listStore, CompanyColumnModelFactory.PROPS.nameLabel(), listView);

    private final DataProxy<PagingLoadConfig, PagingLoadResult<Company> > dataProxy =
            new RpcProxy<PagingLoadConfig, PagingLoadResult<Company>>() {
                @Override
                public void load(PagingLoadConfig loadConfig, final AsyncCallback<PagingLoadResult<Company>> callback) {
                    companyManagement.findCompanies( getText(), loadConfig.getOffset(), loadConfig.getLimit(), callback );
                }
            };

    // List Store

    // Paging Loader
    private final PagingLoader<PagingLoadConfig, PagingLoadResult<Company>> pagingLoader =
            new PagingLoader<PagingLoadConfig, PagingLoadResult<Company>>(dataProxy);

    private LoadCompanyCallback loadCompanyCallback;

    public CompanyComboBox( final LoadCompanyCallback loadCompanyCallback )
    {
        super( comboCell );

        this.loadCompanyCallback = loadCompanyCallback;

        pagingLoader.setRemoteSort(true);
        pagingLoader.addLoadHandler(new LoadResultListStoreBinding<PagingLoadConfig, Company,
                PagingLoadResult<Company>>(listStore));

        listView.setCell(new AbstractCell<Company>() {
            @Override
            public void render(com.google.gwt.cell.client.Cell.Context context, Company company, SafeHtmlBuilder sb) {
                sb.append(template.render( company.getName() != null ? company.getName() : ( company.getLegalName() != null ? company.getLegalName() : "" ),
                        company.getInn() == null ? "" : company.getInn() ) );
            }
        });


        setLoader( pagingLoader);
        setHideTrigger( false );
        setPageSize( 10 );



        setEmptyText( "Введите название клиента, ИНН, ОГРН, паспортные данные..." );

        addBeforeSelectionHandler( new BeforeSelectionHandler<Company>()
        {
            @Override
            public void onBeforeSelection( BeforeSelectionEvent< Company > event )
            {
                event.cancel();
                CompanyComboBox.this.setText( event.getItem().getName() );
                loadCompanyCallback.loadCompany( event.getItem().getId() );

            }
        } );

    }


}
